#!/usr/bin/env python
# -*- coding: utf-8 *-*

#   This file is part of Sql-Rice.
#
#    Sql-Rice is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Sql-Rice is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Sql-Rice; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

import sys
sys.path.append('/archivos/source/sql_rice')

import sql_parse
import gui
import rules
import json
import serialization
import cmd


class DSLRicer(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.config = {}
        self.in_block = ''

    def do_display(self, args):
        self.config['display'] = args

    def do_select(self, args):
        if args == 'begin':
            self.in_block = 'select'
            self.config['select'] = []
        elif args.startswith('ref'):
            ref, path = args.split()
            path = path.replace('"', '')
            with open(path) as f:
                self.config['select'] = f.read()
        elif self.in_block == 'select':
            self.config['select'].append('select ' + args)

    def do_insert(self, args):
        if args == 'begin':
            self.in_block = 'insert'
            self.config['insert'] = []

    def do_update(self, args):
        if args == 'begin':
            self.in_block = 'update'
            self.config['update'] = []

    def do_delete(self, args):
        if args == 'begin':
            self.in_block = 'delete'
            self.config['delete'] = []

    def do_end(self, args):
        if self.in_block:
            self.config[self.in_block] = '\n'.join(self.config[self.in_block])
        self.in_block = ''

    def default(self, line):
        if self.in_block:
            self.config[self.in_block].append(line)


    parse_line = cmd.Cmd.onecmd


class Ricer(object):

    def __init__(self):
        self.sentence = None
        self.widgets = []

    def parse(self, select, insert, update, delete, data_dict):
        self.sentence = sql_parse.Sentence(sql,
                        generate_insert=(insert == 'auto'),
                        generate_update=(update == 'auto'),
                        generate_delete=(delete == 'auto'))
        if  insert not in ('auto', 'off'):
            self.sentence.insert_query = insert
        if update not in ('auto', 'off'):
            self.sentence.update_query = update
        if delete not in ('auto', 'off'):
            self.sentence.delete_query = delete
        table = self.sentence.tables[0]
        for f in self.sentence.fields:
            rule = rules.find(f)
            w = gui.create_widget_info(f, table, data_dict, rule)
            self.widgets.append(w)


def load_dictionary(dictionary):
    with open(dictionary) as f:
        json_obj = json.load(f)
    data_dict = serialization.from_json(json_obj)
    return data_dict


def setup_models(ruledb):
    rules.models.metadata.bind = 'sqlite:///%s' % ruledb
    rules.models.setup_all()


def main(dictionary, ruledb, sqlfile, output):
    data_dict = load_dictionary(dictionary)
    dsr = DSLRicer()
    with open(sqlfile) as f:
        for line in f.readlines():
            dsr.parseline(line)
    select = dsr.config['select']
    insert = dsr.config.get('insert', 'off')
    update = dsr.config.get('update', 'off')
    delete = dsr.config.get('delete', 'off')


    setup_models(ruledb)
    rice = Ricer()
    rice.parse(sql, data_dict)
    with open(output, 'w') as out:
        json.dump(rice, out, default=serialization.to_json, indent=2)

    print 'Done'


main.__annotations__ = dict(
    dictionary='data dictionary file',
    rules='rules file',
    sqlfile='sql script',
    output='rice file out')


if __name__ == '__main__':
    import plac
    plac.call(main)
